/**
 * Created by limei on 2018/6/12.
 */
import MYCONF from '../../myconf'
import MapHelper from '../../util/map-helper'
import DateTimeHelper from '../../util/datetime-helper'
import eventBus from "../../util/event-bus";

export default class homeLayerHandler {
  constructor(_view) {
    this._view = _view;
    this.map = _view.map;
    this.historyMarkers = [];
    this.historyPopups = [];
    this.heatmapIndex = 0;
  }

  addRealPointLayer() {
    const map = this.map;
    let pointList = [];
    // let eTime = DateTimeHelper.getCurTime();
    // let sTime = DateTimeHelper.getMinuteTime(MYCONF.TIME_INTERVAL);
    let url = `${MYCONF.service.real_custom}${this._view.startTime}/${this._view.endTime}`;
    let filterStr = this._view.car_type.type === 0?["!=", "cartype", '']:["==", "cartype", this._view.car_type.type ];
    if (map.getSource('real-custom')) { map.removeSource('real-custom');}
      map.addSource('real-custom', {
        type: 'vector',
        tiles: [url],
      });
    if (map.getLayer('real-custom')) { map.removeLayer('real-custom');}
      map.addLayer({
        "id": "real-custom",
        "source": "real-custom",
        "type": "circle",
        "source-layer": 'gps',
        "paint": {
          "circle-color": {
            "property": "cartype",
            "stops": [
              [1, '#389b34'],
              [2, '#4db22f'],
              [3, '#23b69d'],
              [4, '#6b7fe2'],
              [5, '#ed2323'],
              [6, '#17e0ee'],
            ]
          },
          "circle-radius": 8,
          "circle-blur":0.6,
          "circle-opacity":1,
          "circle-stroke-width":2,
          "circle-stroke-color":"#ffffff",
          "circle-stroke-opacity":0.6,
        },
        "maxzoom": MYCONF.map.PointZoomMax,
        "filter": filterStr
      });
  }
  addRealIconLayer(){
    const map = this.map;
    let url = `${MYCONF.service.real_custom}${this._view.startTime}/${this._view.endTime}`;
    //alert("url是"+url)
    let filterStr = this._view.car_type.type === 0?["!=", "cartype", '']:["==", "cartype", this._view.car_type.type ];
    if (map.getSource('real-icon')) {map.removeSource('real-icon');}
      map.addSource('real-icon', {
        type: 'vector',
        tiles: [url],
      });
    if (map.getLayer('real-icon')) {
      map.removeLayer('real-icon')
    }
     map.addLayer({
        "id": "real-icon",
        "source": "real-icon",
        "type": "symbol",
        "source-layer": 'gps',
        layout: {
          'icon-image': '{caricon}',
          'icon-size': 1,
          // 'icon-rotation-alignment': 'map',
          "icon-allow-overlap": true,  //图标允许压盖
          "icon-ignore-placement": true,  //不被压盖
          "icon-rotate":{
            type: 'identity',
            property: 'cardir'  //图标角度
          }

        },
        "minzoom": MYCONF.map.IconZoomMin,
       "filter": filterStr
      })
  }

  addRealWarnCircleLayer() {
    const map = this.map;
    let url = `${MYCONF.service.real_custom}${this._view.startTime}/${this._view.endTime}`;
    let filterStr = this._view.car_type.type === 0?["!=", "cartype", '']:["==", "cartype", this._view.car_type.type];
    if (map.getSource('real-warn-circle')) { map.removeSource('real-warn-circle');}
     map.addSource('real-warn-circle', {
        type: 'vector',
        tiles: [url],
      });
    if (map.getLayer('real-warn-circle')) { map.removeLayer('real-warn-circle');}
     map.addLayer({
        "id": "real-warn-circle",
        "source": "real-warn-circle",
        "type": "symbol",
        "source-layer": 'gps',
        layout: {
          'icon-allow-overlap': true,
          "icon-ignore-placement": true,
          'icon-image': 'redring',
          'icon-size': 1,
          'icon-rotation-alignment': 'map'
        },
        "minzoom": MYCONF.map.IconZoomMin,
        "filter": ['all',["in", "carid", ...this._view.warnCarIds],filterStr]
      })
  }

  addRealWarnIconLayer() {
    const map = this.map;
    let url = `${MYCONF.service.real_custom}${this._view.startTime}/${this._view.endTime}`
    let filterStr = this._view.car_type.type === 0?["!=", "cartype", '']:["==", "cartype", this._view.car_type.type ];
    if (map.getSource('real-warn-icon')) { map.removeSource('real-warn-icon');}
      map.addSource('real-warn-icon', {
        type: 'vector',
        tiles: [url],
      });
    if (map.getLayer('real-warn-icon')) { map.removeLayer('real-warn-icon');}
      map.addLayer({
        "id": "real-warn-icon",
        "source": "real-warn-icon",
        "type": "symbol",
        "source-layer": 'gps',
        layout: {
          'icon-allow-overlap': true,
          'icon-image': 'warncar',
          'icon-size': 0.7,
          'icon-rotation-alignment': 'map',
          "icon-ignore-placement": true,
          "icon-offset": [20, 20]
        },
        "minzoom": MYCONF.map.IconZoomMin,
        "filter": ['all',["in", "carid", ...this._view.warnCarIds],filterStr]
      })
  }

  addHotMapLayer(date, type) {
    // console.log("这里添加多车历史热力图图层", date); //这里添加多车历史热力图图层
    const map = this.map;
    for (let i = 0; i < 24; i++) {
      if (!map.getSource('history-heatmap' + i)) {
        map.addSource('history-heatmap' + i, {
          type: 'vector',
          tiles: [`${MYCONF.service.historyHeatmap}[${date}${DateTimeHelper.formTime(i)}0000,${i === 23 ? DateTimeHelper.getNextDay(date) : date}${DateTimeHelper.formTime(i === 23 ? 0 : (i + 1))}0000]`],
        })
      }
      if (!map.getLayer('history-heatmap' + i)) {
        map.addLayer({
          "id": "history-heatmap" + i,
          "source": "history-heatmap" + i,
          "type": "heatmap",
          "source-layer": 'gps',
          "layout": {
            "visibility": "none"
          },
          "paint": {
            // 一个热力图数据点的模糊范围，单位是像素，默认值30；要求：值大于等于1，可根据zoom level进行插值设置
            "heatmap-radius": 30,
            // 用于统一控制热力值的强度，默认值1；要求：值大于等于0，可根据zoom level进行插值设置
            "heatmap-intensity": 1,
            // 表示热力图颜色阶梯，阶梯的值域范围为0-1，默认值为["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"]
            "heatmap-color": [
              "interpolate", ["linear"],
              ["heatmap-density"],
              0, "rgba(0, 0, 255, 0)", 0.1, "royalblue", 0.3, "cyan", 0.5, "lime", 0.7, "yellow", 1, "red"
            ],
            // 表示热力图的不透明度，默认值1；值域范围0-1，可根据zoom level进行插值设置
            "heatmap-opacity": 1,
          },
          "filter": type.type !== 0 ? ['==', 'cartype', type.type] : ['!=', 'cartype', '']
        })
      }
    }

    // map.moveLayer('history-heatmap0');
    map.setLayoutProperty('history-heatmap0', 'visibility', 'visible');
    this.heatmapIndex = 0;
  }

  changeHeatmapLayer(index) {
    const map = this.map;
    // map.moveLayer(`history-heatmap${this.heatmapIndex}`, myconf.BACKGROUND_LAYER_ID);
    // map.moveLayer(`history-heatmap${index}`);

    map.setLayoutProperty(`history-heatmap${this.heatmapIndex}`, 'visibility', 'none');
    map.setLayoutProperty(`history-heatmap${index}`, 'visibility', 'visible');

    this.heatmapIndex = index;
  }

  addHisSingleLayer() {
    console.log("这里添加单车历史逻辑");
  }

  addRealSingleLayer() {
    const map = this.map;
    let point = this._view.realSingleData[0]?this._view.realSingleData[0].point.slice(0,2):this._view.fCoordinate;
    let point2 = this._view.realSingleData[0]?this._view.realSingleData[0].point.slice(0,2):this._view.eCoordinate;

    this.addSingleCar(point);
    this.addRealSinglePath(point,point2);
    if(this._view.home_state === 'realtime_single') this.setRealSingleTimer();
  }

  addRealGroupLayer() {
    const map = this.map;
    let eTime = DateTimeHelper.getCurTime();
    let sTime = DateTimeHelper.getMinuteTime(MYCONF.TIME_INTERVAL);
    //let url = `${MYCONF.service.real_custom}${this._view.startTime}/${this._view.endTime}`;
    let url = `${MYCONF.service.real_company}${this._view.company_info.id}/${sTime}/${eTime}`;
    if (map.getSource('real-group')) { map.removeSource('real-group');}
      map.addSource('real-group', {
        type: 'vector',
        tiles: [url],
      });
    if (map.getLayer('real-group')) { map.removeLayer('real-group');}
      map.addLayer({
        "id": "real-group",
        "source": "real-group",
        "type": "circle",
        "source-layer": 'gps',
        "paint": {
          "circle-color": {
            "property": "cartype",
            "stops": [
              [1, '#389b34'],
              [2, '#4db22f'],
              [3, '#23b69d'],
              [4, '#6b7fe2'],
              [5, '#ed2323'],
              [6, '#17e0ee'],
            ]
          },
          "circle-radius": 8,
          "circle-blur":0.6,
          "circle-opacity":1,
          "circle-stroke-width":2,
          "circle-stroke-color":"#ffffff",
          "circle-stroke-opacity":0.5,
        },
        "maxzoom": MYCONF.map.PointZoomMax,
      })
    if (map.getSource('group-icon')) { map.removeSource('group-icon');}
      map.addSource('group-icon', {
        type: 'vector',
        tiles: [url],
      })
    if (map.getLayer('group-icon')) { map.removeLayer('group-icon');}
      map.addLayer({
        "id": "group-icon",
        "source": "group-icon",
        "type": "symbol",
        "source-layer": 'gps',
        layout: {
          'icon-image': '{caricon}',
          'icon-size': 1,
          'icon-rotation-alignment': 'map',
          "icon-allow-overlap": true,  //图标允许压盖
          "icon-ignore-placement": true,
          'icon-rotate': {
            type: 'identity',
            property: 'dir'
          },
        },
        "minzoom": MYCONF.map.IconZoomMin,
      })

  }

  drawHistoryPath(pointList) {
   // alert("draw");
    this._view.updateLoadingState(true);
    let map = this.map;
    let wholePath = turf.lineString(pointList);
    let bbox = turf.bbox(wholePath);

    map.stop();
    map.fitBounds([[bbox[0], bbox[1]], [bbox[2], bbox[3]]], {
      linear: true,
      padding: {
        top: 10,
        bottom: 10,
        left: 50,
        right: 50
      }
    });
    //padding取大值报错，故，fitBounds以后缩小一级别
    map.once('zoomend', () => {
      map.zoomOut();
    });

    if (map.getSource('whole-path')) {
      map.getSource('whole-path').setData(wholePath);
    } else {
      if (map.getSource('whole-path')) return;
      map.addSource('whole-path', {
        type: 'geojson',
        data: wholePath
      });

      map.addLayer({
        id: 'whole-path',
        source: 'whole-path',
        type: 'line',
        layout: {
          'line-cap': 'round',
          'line-join': 'round',
        },
        paint: {
          'line-color': '#4e9c98',
          'line-width': 5,
          "line-opacity": 0.4
        }
      // }, MYCONF.map.roadName);
      });
    }

    setTimeout(() => {
      this._view.updateLoadingState(false);
    }, 500)
  }

  addHistoryPath(pointList, layerBefore) {
   // alert("add");
    const map = this.map;
    if (map.getSource('history-path')) return;
    map.addSource('history-path', {
      type: 'geojson',
      data: {
        'type': 'Feature',
        'geometry': {
          'type': 'LineString',
          'coordinates': pointList ? pointList : [[116.40717, 39.90469], [116.40717, 39.90469]]
        }
      }
    });

    map.addLayer({
      id: 'history-path',
      source: 'history-path',
      type: 'line',
      layout: {
        'line-cap': 'round',
        'line-join': 'round',
      },
      paint: {
        'line-color': '#7DEDE9',
        'line-width': 5
      }

      // }, layerBefore || MYCONF.map.roadName)
    })
  }

  addRealSinglePath(point,point2){
    const map = this.map;
    if (map.getSource('real-path')) return;
    map.addSource('real-path', {
      type: 'geojson',
      data: {
        'type': 'Feature',
        'geometry': {
          'type': 'LineString',
          'coordinates': [point,point2]
        }
      }
    });

    map.addLayer({
      id: 'real-path',
      source: 'real-path',
      type: 'line',
      layout: {
        'line-cap': 'round',
        'line-join': 'round',
      },
      paint: {
        'line-color': '#7DEDE9',
        'line-width': 5
      }
    },'single-car')
  }

  addSymbolLayer(type, point) {
    const map = this.map;
    let layerId = type + "Symbol";
    if (map.getLayer(layerId)) map.removeLayer(layerId);
    map.addLayer({
      "id": layerId,
      "type": "symbol",
      "source": {
        "type": "geojson",
        "data": {
          "type": "FeatureCollection",
          "features": [{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": point
            }
          }]
        }
      },
      "layout": {
        "icon-image": type,
        "icon-size": 0.5,
        "icon-allow-overlap": true,  //图标允许压盖
        "icon-ignore-placement": true,
      }
    });
  }

  getRealSingleData() {
    let _this = this;
    // let url = './static/data/realPath.json';
    // let url = MYCONF.service.realSingleCar+'[\"'+this._view.single_car.id+'\"]';
    let afterDate= DateTimeHelper.getAfterMinuteTime(5);
    let beforeDate = DateTimeHelper.getMinuteTime(5);
    let firstPoint=this._view.fCoordinate?`${this._view.fCoordinate[0]},${this._view.fCoordinate[1]}`:'0';
    let secondPoint=this._view.eCoordinate?`${this._view.eCoordinate[0]},${this._view.eCoordinate[1]}`:'0';
    let secondTime = this._view.secondTime?`${this._view.secondTime}`:'0';
    let pointStr = `&firstPoint=${firstPoint}&secondPoint=${secondPoint}`;
    let date = DateTimeHelper.getCurDate();
    let url = MYCONF.service.realSingleCar2+this._view.single_car.id+'&angleLeavel=5'+'&distance=10.0'+'&secondTime='+secondTime+'&beforeDate='+beforeDate+'&afterDate='+afterDate+'&date='+date+'&lastAngle='+this._view.singleAngle+pointStr;

    this._view.$http.get(url)
      .then(response => {
        response = response.body;

        if(response && response.state === 1){
          this._view.realSingleData = response.result.data;
          let curData = response.result.data;
          this._view.sTime = curData[0].time;
          this._view.eTime = curData[curData.length-1].time;
          this._view.fCoordinate = curData[0].point.slice(0,2);
          // this._view.singleAngle = curData[curData.length-1].point[3];
          this._view.eCoordinate = curData[curData.length-1].point.slice(0,2);
          this._view.secondTime = curData[curData.length-1].time;
          this._view.updateSingleCar({
            time:response.time,
          });
        }else if(response && response.state === 0 && this._view.home_state ==='realtime_single'){
          this._view.secondTime = 0;
          _this._view.mapHandler.updateSpeedMarker(this._view.mapCenter,0);
          setTimeout(() => {
            eventBus.$emit("getRealSingleData");
          },MYCONF.SINGLE_PATH_INTERVAL);
        }
        // eventBus.$emit('updateSingleWarnList',this._view.sTime,this._view.eTime);    //To homeView.vue
      }, response => {
        // this._view.fCoordinate = null;
        // this._view.eCoordinate = null;
        clearInterval(this._view.realTimer);
        // error callback
      });
  }

  addWarnInfo(mapCenter, warnInfo) {
    let map = this.map;
    let warnToggle = false;
    let el = MapHelper.addNormalMarker("warn");
    let popup = null;
    let warnText = null;
    switch (warnInfo.warnflag) {
      case 'pressingup':
        warnText = "急加速";
        break;
      case 'pressingdown':
        warnText = "急减速";
        break;
      case 'pressingturn':
        warnText = "急转弯";
        break;
      case 'tireddrive':
        warnText = "疲劳驾驶";
        break;
      case 'notflameout':
        warnText = "停车未熄火超时";
        break;
      case 'parked':
        warnText = "停车统计";
        break;
      case 'speed':
        warnText = "超速";
        break;
      case 'weight':
        warnText = "超重";
        break;
      default:
        warnText = "违规";
        break;
    }
    // let warnText = curWarnFlag === "speed" ? "超速" : curWarnFlag === "weight" ? "超重" : "其他";
    let marker = new minemap.Marker(el, {offset: [-10, -10]})
      .setLngLat(mapCenter);
    setTimeout(() => {
      marker.addTo(map);
      popup = new minemap.Popup({closeOnClick: false, offset: [0, -30]})
        .setLngLat(mapCenter)
        .setDOMContent(MapHelper.addNormalPopup(warnText))
        .addTo(map);

      this.historyMarkers.push(marker);
      this.historyPopups.push(popup);
    }, 800);

    el.onclick = () => {
      warnToggle = !warnToggle;
      // let time = DateTimeHelper.timestampToTime(point.timestamp);
      let time = this.setTimeFormat(warnInfo.timestamp);
      if (warnToggle) {
        popup.setDOMContent(MapHelper.addWarnPopup(warnInfo, this._view.single_car, time));
      } else {
        popup.setDOMContent(MapHelper.addNormalPopup(warnText));
      }
    }
  }

  setTimeFormat(timeStr) {
    let tempArr = [];
    if (timeStr.toString().indexOf("-") !== -1) {
      timeStr.split("-").map((time, index) => {
        if (tempArr[0] && tempArr[0].split(" ")[0] === DateTimeHelper.timestampToTime(time).split(" ")[0]) {   //同一天
          tempArr.push(DateTimeHelper.timestampToTime(time).split(" ")[1]);
        } else {
          tempArr.push(DateTimeHelper.timestampToTime(time));
        }
      });
    } else {
      tempArr.push(DateTimeHelper.timestampToTime(timeStr));
    }
    return tempArr.join(" ~ ");
  }

  //实时单车轨迹的图层
  addSingleCar(point,type=1) {
    const map = this.map;
    let iconType = 'car-'+type;
    let iconImg = this._view.home_state === 'alarm_info'?iconType:this._view.single_car.carType?'car-'+this._view.single_car.carType:'car-1';
    if (map.getSource('single-car')) return;
    // map.flyTo({
    //   center: point
    // });
    map.addSource('single-car', {
      type: 'geojson',
      data: {
        'type': 'FeatureCollection',
        'features': [{
          'type': 'Feature',
          'geometry': {
            'type': 'Point',
            'coordinates': point ? point : [116.40717, 39.90469]
          }
        }]
      }
    });
    map.addLayer({
      id: 'single-car',
      source: 'single-car',
      type: 'symbol',
      layout: {
        'icon-image': iconImg,
        'icon-size': 1,
        'icon-rotation-alignment': 'map',
        "icon-allow-overlap": true,  //图标允许压盖
        "icon-ignore-placement": true,
      }
    })
  }

  //单车实时timer
  setRealSingleTimer(){
    const map = this._view.map;
    let _this = this;
    let curPoint = _this._view.realSingleData[0];
    let mapCenter = _this._view.realSingleData[0].point.slice(0,2);
    let curAngle = this._view.singleAngle;
    let curSpeed = 0;
    let curVal = 0;
    let realPath = this._view.realData;
    map.flyTo({
      center: mapCenter,
      // zoom:14,
      speed:1.6
    });
    _this._view.realTimer = setInterval(() => {
      if (curVal < this._view.realSingleData.length-1) {
        curVal++;     //第n+1个点
      } else {
        // this._view.singleAngle = _this._view.realSingleData[_this._view.realSingleData.length-1].point[3];
        this._view.mapCenter = mapCenter;
        map.flyTo({
          center: mapCenter,
          // zoom:14,
          speed:1.6
        });
        this._view.singleAngle = curPoint.point[3];
        // console.log(this._view.singleAngle);
        _this._view.mapHandler.updateSpeedMarker(mapCenter,0);
        clearInterval(_this._view.realTimer);
        _this.getRealSingleData();     //请求下一分钟
        // curVal = 0;
      }
      curPoint = _this._view.realSingleData[curVal];
      curAngle = curPoint.point[3];
      // console.log("++++",curAngle);
      mapCenter = curPoint.point.slice(0, 2);
      curSpeed = curPoint.speed;
      // console.log(_this._view.realSingleData[0].time,_this._view.realSingleData[_this._view.realSingleData.length-1].time);
      realPath.push(mapCenter);
      this._view.realData.push(mapCenter);
      let geo = turf.point(mapCenter);
      map.getSource('single-car').setData(geo);
      map.setLayoutProperty('single-car', 'icon-rotate', curAngle);
      //console.log("当前角度：",curAngle);
      if (this.isUpdateCenter(mapCenter)) {
        map.flyTo({
          center: mapCenter,
          speed: 1.8
        });
      }
      _this._view.mapHandler.updateSpeedMarker(mapCenter,curSpeed);

      if (realPath.length > 1) {
        let realLine = turf.lineString(realPath);
        map.getSource('real-path').setData(realLine);
      }

      if(curVal % 10 === 0){
        map.flyTo({
          center: mapCenter,
          speed:1.6
        });
      }
    },1000);
  }
  setAxisTimer() {
    const map = this.map;
    let curHour = this._view.axis_num.hour;  //历史播放的当前小时
    let curVal = this._view.axis_num.index;   //历史播放的当前点
    let historyData = this._view.historyData;  //总的历史数据
    let curPoint = {};
    let mapCenter = [];
    let curAngle = 0;
    let curSpeed = 0;
    if(historyData[curHour]!=undefined){
      let curHourData = historyData[curHour].data;//当前小时历史数据

      let pathList = this._view.hisData ? this._view.hisData : [];    //轨迹点集合
      let _this = this;
      map.stop();
      map.flyTo({
        center: curHourData[curVal].point.slice(0, 2),
        zoom: 14,
        speed: 1.8
      });
      //console.log("刷新时间：",this._view.speed)
      _this._view.historyTimer = setInterval(() => {
        //时间轴跑完一程清零
        if (curVal < 599) {
          curVal++;     //第n+1个点
        } else {
          curVal = 0;
          curHour++;
          curHourData = historyData[curHour].data;
        }
        eventBus.$emit("autoMovingInterval", {val: curVal, index: curHour});
        curPoint = curHourData[curVal];
        curAngle = curPoint.point[3];
        mapCenter = curPoint.point.slice(0, 2);
        curSpeed = curPoint.speed;

        _this._view.mapHandler.updateSpeedMarker(mapCenter,curSpeed);

        let geo = turf.point(mapCenter);
        map.getSource('single-car').setData(geo);
        if (this.isUpdateCenter(mapCenter)) {
          map.flyTo({
            center: mapCenter,
            speed: 1.8
          });
        }
        curSpeed = parseInt(curPoint.speed);

        map.setLayoutProperty('single-car', 'icon-rotate', curAngle);
        pathList.push(mapCenter);
        // this.context.hisData = hisData;
        if (pathList.length > 1) {
          let hisPath = turf.lineString(pathList);
          if(map.getSource('history-path')){
            map.getSource('history-path').setData(hisPath);
          }else {
            console.log("无历史轨迹")
          }
        }

        if ((curHour === 23 && curVal >= 599)) {
          clearInterval(this._view.historyTimer);  //跑完
          this._view.hisData = [];
          this._view.updateAxisNum({
            hour: 0,
            index: 0
          });
          eventBus.$emit("historyFinish");
        }

      }, this._view.speed);
    }

  }

  addAlarmLayer(){
    const map = this._view.map;
    let alarmInfo = this._view.alarmInfo;
    let coordinate = [alarmInfo.lon,alarmInfo.lat];
    let type = alarmInfo.carType;
    this.addSingleCar(coordinate,type);
    map.stop();
    map.flyTo({
      center:coordinate,
      zoom:14,
      speed:1.8
    })
  }

  filterHomePointLayer(){
    const map = this._view.map;
    let type = this._view.car_type.type;
    if(this._view.car_type.type === 0){
      if(map.getLayer('real-custom')) map.setFilter('real-custom',['!=', 'cartype', '']);
      if(map.getLayer('real-icon')) map.setFilter('real-icon',['!=', 'cartype', '']);
      if(map.getLayer('real-warn-circle')) map.setFilter('real-warn-circle',["in", "carid", ...this._view.warnCarIds]);
      if(map.getLayer('real-icon')) map.setFilter('real-icon',["in", "carid", ...this._view.warnCarIds]);
      for (let i = 0; i < 24; i++) {
        if (map.getLayer('history-heatmap' + i)) map.setFilter('history-heatmap' + i, ['!=', 'cartype', '']);
      }
      console.log(0)
    }else{
      if(map.getLayer('real-custom')) map.setFilter('real-custom',['==', 'cartype', type]);
      if(map.getLayer('real-icon')) map.setFilter('real-icon',['==', 'cartype', type]);
      if(map.getLayer('real-warn-circle')) map.setFilter('real-warn-circle',['all',["in", "carid", ...this._view.warnCarIds],["==", "cartype",type]]);
      if(map.getLayer('real-icon')) map.setFilter('real-icon',['all',["in", "carid", ...this._view.warnCarIds],["==", "cartype",type]]);
      for (let i = 0; i < 24; i++) {
        if (map.getLayer('history-heatmap' + i)) map.setFilter('history-heatmap' + i, ['==', 'cartype', type]);
      }
      console.log(type)
    }
  }

  isUpdateCenter(pos) {
    const map = this._view.map;
    let point = map.project([pos[0], pos[1]]);
    if (((point.x < 600 || document.body.clientWidth - point.x) < 600 || point.y < 500 || (document.body.clientHeight - point.y) < 500) && !this._view.isMapDraged) {
      return true;
    } else {
      return false;
    }
  }


  clearHomeMap() {
    const map = this._view.map;
    map.removeMarkers(this.historyMarkers);
    this.historyPopups.map((popup) => {
      popup.remove();
    });
  }

  changeMapCenterAndZoom(center, zoom) {
    const map = this._view.map;
    map.easeTo({
      center,
      zoom
    });
  }
}
